from django.shortcuts import render, redirect, reverse
from SelectApp import models
from django.http import HttpResponse, JsonResponse
from django import views
from SelectApp.Myforms import RegisterForm
from SelectApp.util import get_md5

# Create your views here.


def register(request):
    if request.method == 'GET':
        obj = RegisterForm()
        return render(request, 'register.html', {'obj': obj})
    if request.method == 'POST':
        obj = RegisterForm(request.POST)
        if obj.is_valid():
            obj.cleaned_data.pop('confirm_password')
            password = obj.cleaned_data.get('password')
            obj.cleaned_data.update({'password': get_md5(password)})
            models.User.objects.create(**obj.cleaned_data)
            return redirect('select:login')
        else:
            return render(request, 'register.html', {'obj': obj})


def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        msg = {'status': True, 'error': None}
        user = request.POST.get('user')
        password = request.POST.get('password')
        password = get_md5(password)
        obj = models.User.objects.filter(user=user).first()
        if obj:
            if obj.password == password:
                request.session['is_login'] = True
                request.session['name'] = obj.name
                request.session['user'] = user
                return JsonResponse(msg)
            else:
                msg['status'] = False
                msg['error'] = '您输入的密码有误'
                return JsonResponse(msg)
        else:
            msg['status'] = False
            msg['error'] = '您输入的用户名不存在'
            return JsonResponse(msg)


def index(request):
    if request.method == 'GET':
        return render(request, 'index.html')
    if request.method == 'POST':
        city = request.POST.get('city')
        if city:
            return redirect('select:display', city)
        else:
            return render(request, 'index.html', {'error': '请输入搜索内容'})


def out(request):
    request.session.clear()
    return redirect('select:login')


class Display(views.View):
    def get(self, request, city):
        result = models.MeituanSpider.objects.filter(city=city).all()
        if result:
            return render(request, 'display.html', {'result': result})
        else:
            return HttpResponse('你所查找的城市不存在')

    def post(self):
        pass


def detail(request, id):
    if request.method == 'GET':
        result = models.MeituanSpider.objects.filter(shopId=id).first()
        deal_list = result.deal.split(';')
        return render(request, 'detail.html', {'detail': result, 'deal': deal_list})
